﻿using EFCore.BulkExtensions;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using PrivateTracker.Service.Core;

namespace PrivateTracker.Service.Application;
/// <summary>
/// 
/// </summary>
public class PeerSevice : IPeerService, ITransient
{
    private readonly ITorrentService _torrentService;
    private readonly IRepository<Peer> _repository;
    /// <summary>
    /// 
    /// </summary>
    public PeerSevice(ITorrentService torrentService, IRepository<Peer> repository)
    {
        _torrentService = torrentService;
        _repository = repository;
    }
    /// <summary>
    /// 添加做种Peer
    /// </summary>
    /// <param name="announceInput"></param>
    /// <param name="torrentId"></param>
    /// <returns></returns>
    public async Task<IList<Peer>> AddPeerAsync(AnnounceInput announceInput, long torrentId)
    {
        IList<Peer> peers = new List<Peer>();
        //Ipv4的peer
        peers.Add(new Peer
        {
            TorrentId = torrentId,
            PeerId = announceInput.Peer_Id,
            Agent = announceInput.GetAgent(),
            DownLoaded = announceInput.Downloaded,
            Uploaded = announceInput.Uploaded,
            Ip = announceInput.GetIPv4(),
            Port = announceInput.Port,
            PrevActon = DateTimeOffset.Now,
            LastActon = DateTimeOffset.Now
        });
        //同时具有Ipv6
        string ipv6 = announceInput.GetIPv6();
        if (!string.IsNullOrWhiteSpace(ipv6))
        {
            peers.Add(new Peer
            {
                TorrentId = torrentId,
                PeerId = announceInput.Peer_Id,
                Agent = announceInput.GetAgent(),
                DownLoaded = announceInput.Downloaded,
                Uploaded = announceInput.Uploaded,
                Ip = announceInput.GetIPv6(),
                Port = announceInput.Port,
                PrevActon = DateTimeOffset.Now,
                LastActon = DateTimeOffset.Now
            });
        }
        await _repository.InsertNowAsync(peers);
        return await _repository.DetachedEntities.Where(p => p.TorrentId == torrentId).ToListAsync();
    }

    /// <summary>
    /// 删除peer
    /// </summary>
    /// <param name="torrentId"></param>
    /// <param name="peerId"></param>
    /// <returns></returns>
    public async Task DeletePeerAsync(long torrentId, string peerId)
    {
        await _repository.Where(p => p.PeerId == peerId && p.TorrentId == torrentId).BatchDeleteAsync();
    }
}
